package com.hnust.controller.student;

//import com.hnust.domain.Data;

import com.hnust.domain.CourseData;
import com.hnust.domain.Result;
import com.hnust.domain.StuDetailSubjectData;
import com.hnust.domain.StudentDetailAndTotal;
import com.hnust.fx.FXMLController;
import com.hnust.service.StudentService;
import com.hnust.service.SubjectService;
import com.hnust.service.TestPaperService;
import com.hnust.store.DataStore;
import com.hnust.store.StudentDetailDataStore;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import org.springframework.beans.factory.annotation.Autowired;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;

@FXMLController
public class DetailDataController implements Initializable {
    @FXML
    AnchorPane detail;
    @Autowired
    private DataStore dataStore;
    @Autowired
    private StudentDetailDataStore studentDetailDataStore;
    @Autowired
    private TestPaperService testPaperService;
    @FXML
    VBox vBoxId;
    @FXML
    ComboBox<String> courseCom;
    @FXML
    TableView<StuDetailSubjectData> tableDetail;
    @FXML
    TextField className;
    @FXML
    TextField stuName;
    @FXML
    public Pagination toPage;
    @FXML
    private Label dataCount;
    @FXML
    private Label dataRows;
    @FXML
    private Label dataPages;
    @Autowired
    private StudentService studentService;


    private ObservableList<StuDetailSubjectData> list1 = FXCollections.observableArrayList();
    private ObservableList<StuDetailSubjectData> list2 = FXCollections.observableArrayList();
    private List<CourseData> list=new ArrayList<>();
    private ObservableList<String> courseList=FXCollections.observableArrayList();
    private String claName=null;
    private String studentName=null;
    private String courseName=null;
    private Integer currentPage=1;
    private int flag=0;
    private List<CourseData> courseDataList=new ArrayList<>();
    private String allValue="全部";
    private String defaultValue="暂未加入课程组";

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        /*表格自适应*/
        detail.parentProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
               // getStuInfo();
                getCombData();
                toPage.setPageCount(1);
            }else{
                list1.clear();
                courseList.clear();
                tableDetail.getItems().clear();
            }
        });
        pageListener();

    }


    public void getStuInfo() {
        studentService.getCourseInfo(new Callback<Result<StudentDetailAndTotal>>() {
            @Override
            public void onResponse(Call<Result<StudentDetailAndTotal>> call, Response<Result<StudentDetailAndTotal>> response) {
                //System.out.println(response.body());
                Result<StudentDetailAndTotal> result=response.body();
                assert result != null;
                Platform.runLater(() -> {
                    list1.clear();
                    courseList.clear();

                    result.getData().getList().forEach(info -> {
                        list1.add(new StuDetailSubjectData());
                    });

                    studentDetailDataStore.setList(list1);

                    ObservableList<StuDetailSubjectData> stuDetailSubjectData=FXCollections.observableArrayList(result.getData().getList());
                    tableDetail.setItems(stuDetailSubjectData);

                    for (StuDetailSubjectData detailSubjectData : result.getData().getList()) {
                        courseList.add(detailSubjectData.getCourse());
                    }
                    HashSet<String> hashSet = new HashSet<>(courseList);
                    courseList=FXCollections.observableArrayList(hashSet);
                    toPage.setPageCount(0);
                    setPage(result.getData().getTotal());
                    courseCom.setItems(courseList);
                });
            }

            @Override
            public void onFailure(Call<Result<StudentDetailAndTotal>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                    alert.showAndWait();
                });
            }
        },dataStore.getTeacher_id(),dataStore.getToken(),null,null,null,currentPage);

    }
    //获取课程信息
    public void getCombData(){
        //获取老师所加入课程的信息
        testPaperService.getCourseData(new retrofit2.Callback<Result<List<CourseData>>>() {
            @Override
            public void onResponse(Call<Result<List<CourseData>>> call, Response<Result<List<CourseData>>> response) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        courseList.clear();
                        courseDataList.clear();
                        courseDataList=response.body().getData();
                        if(courseDataList.size()!=0){
                            courseList.add(allValue);
                            courseDataList.forEach(courseData -> {
                                courseList.add(courseData.getName());
                            });
                        }else{
                            courseList.add(defaultValue);
                        }
                        setCourseNameCombox();
                    }
                });
            }
            @Override
            public void onFailure(Call<Result<List<CourseData>>>call, Throwable t) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        },dataStore.getTeacher_id(),dataStore.getToken());

    }

    //设置Combox
    public void setCourseNameCombox(){
        courseCom.setItems(courseList);
        if(courseList.size()==1&&courseList.get(0).equals(defaultValue)){
            courseCom.getSelectionModel().select(0);
        }
        courseCom.selectionModelProperty().addListener(new ChangeListener<SingleSelectionModel<String>>() {
            @Override
            public void changed(ObservableValue<? extends SingleSelectionModel<String>> observable, SingleSelectionModel<String> oldValue, SingleSelectionModel<String> newValue) {
                flag=1;
            }
        });
    }
    //查询按钮
    public void search() {
        claName = className.getText();
        studentName = stuName.getText();
        courseName = (String) courseCom.getValue();
        toPage.setPageCount(0);
        if( claName.length()!=0 && claName.charAt(claName.length()-1) == '班') {
            claName = claName.substring(0,claName.length()-1);
//            System.out.println(claName.length());
        }

        if(studentName.isEmpty() && claName.isEmpty() && courseName == null) {
            getStuInfo();
        }
        else {
            studentService.getCourseInfo(new Callback<Result<StudentDetailAndTotal>>() {
                @Override
                public void onResponse(Call<Result<StudentDetailAndTotal>> call, Response<Result<StudentDetailAndTotal>> response) {
                    Result<StudentDetailAndTotal> result=response.body();
                    assert result != null;
                    Platform.runLater(() -> {
                        list1.clear();
                        result.getData().getList().forEach(info -> {
                            list1.add(new StuDetailSubjectData());
                        });
                        setPage(result.getData().getTotal());
                        studentDetailDataStore.setList(list1);
                        ObservableList<StuDetailSubjectData> stuDetailSubjectData = FXCollections.observableArrayList(response.body().getData().getList());
                        tableDetail.setItems(stuDetailSubjectData);

                    });
                }

                @Override
                public void onFailure(Call<Result<StudentDetailAndTotal>> call, Throwable throwable) {
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                        alert.showAndWait();
                    });
                }
            }, dataStore.getTeacher_id(), dataStore.getToken(), claName, studentName, courseName,currentPage);

        }

    }

    public void pageListener() {
        toPage.currentPageIndexProperty().addListener((observable, oldValue, newValue) -> {
            currentPage=newValue.intValue()+1;
            search();
        });
    }

    public void setPage(int len){
        int a=len/10;
        if(len%10!=0){
            a++;
        }
        toPage.setPageCount(a);
        dataPages.setText("共"+a+"页");
        dataRows.setText("每页13条");
        dataCount.setText("共有"+len+"条数据");
    }

    public void setPageSearch(int len){
        int a=len/10;
        if(len%10!=0){
            a++;
        }
        toPage.setPageCount(a);
        dataPages.setText("共"+a+"页");
        dataRows.setText("");
        dataCount.setText("共有"+len+"条数据");
    }
}
